//
//  PhotoBrowserViewController.m
//  kuangjia
//
//  Created by 张帅 on 15/10/14.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "PhotoBrowserViewController.h"
#import "UIButton+bottom.h"
#import "PhotoBrowserCell.h"
#import "UIColor+extension.h"
#import <SVProgressHUD.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
@interface PhotoBrowserViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,PhotoBrowserCellDelegate,UIViewControllerInteractiveTransitioning,UIViewControllerContextTransitioning>


@property(nonatomic,strong) UICollectionView *collectionView;

@property(nonatomic,strong) UIButton *saveButton;


@property(nonatomic,strong) UIButton *closeButton;


@property(nonatomic,strong) UIPageControl *pageControl;

@property(nonatomic,assign) CGFloat photoScale;


@end


@implementation PhotoBrowserViewController





-(NSIndexPath *)currentImageIndex{

    return self.collectionView.indexPathsForVisibleItems.lastObject;

}


/// 当前选中的图像视图

-(UIImageView *)currentImageView{
    
    
    PhotoBrowserCell *cell =(PhotoBrowserCell*)[self.collectionView cellForItemAtIndexPath:self.currentImageIndex]  ;
 
    return cell.imageView;
}

static NSString * HMPhotoBrowserCellID = @"HMPhotoBrowserCellID";


-(instancetype)initWithURL:(NSMutableArray *)urls indexPath:(NSIndexPath *)indexPath{

    self.urls=urls;
    
    self.selectedIndexPath =indexPath;
    
    return [super initWithNibName:nil bundle:nil];
    
}


-(void)loadView{

    CGRect rect =[UIScreen mainScreen].bounds;
    rect.size.width+=20;
    
    self.view=[[UIView alloc] initWithFrame:rect];
    
    self.view.backgroundColor =[UIColor blackColor];
    
    [self setupUI];

}


-(void)viewDidLayoutSubviews{

    [super viewDidLayoutSubviews];
    
     // collectionView 滚动到用户选择的图片
    
    [self.collectionView scrollToItemAtIndexPath:self.selectedIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    self.pageControl.currentPage =self.selectedIndexPath.item;
    
}


-(void)viewDidLoad{

    [super viewDidLoad];
    NSLog(@"%@",self.urls);
    
    NSLog(@"%@",self.selectedIndexPath);
    

}

-(void)setupUI{

    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.closeButton];
    [self.view addSubview:self.saveButton];
    [self.view addSubview:self.pageControl];
    
    self.collectionView.frame =self.view.bounds;
    
    self.closeButton.translatesAutoresizingMaskIntoConstraints =NO;
    self.saveButton.translatesAutoresizingMaskIntoConstraints =NO;
    self.pageControl.translatesAutoresizingMaskIntoConstraints=NO;
    
    
    NSDictionary *dict =@{@"sv":self.saveButton,@"cv":self.closeButton};
    
    
    [self.view addConstraints:[NSLayoutConstraint  constraintsWithVisualFormat:@"H:|-8-[sv(80)]-(>=8)-[cv(80)]-30-|" options:0 metrics:nil views:dict]];
    
    
    [self.view addConstraints:[NSLayoutConstraint  constraintsWithVisualFormat:@"V:[sv(50)]-12-|" options:0 metrics:nil views:dict]];
    
    [self.view addConstraints:[NSLayoutConstraint  constraintsWithVisualFormat:@"V:[cv(50)]-12-|" options:0 metrics:nil views:dict]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl attribute:(NSLayoutAttributeCenterX) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:-12]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.pageControl attribute:(NSLayoutAttributeBottom) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-13]];
    
    
    
    __weak typeof(self)wself =self;
    
    [[self.closeButton rac_signalForControlEvents:(UIControlEventTouchUpInside)]subscribeNext:^(id x) {
      
        [wself dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [[self.saveButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
       
        [wself saveImage];
    } completed:^{
        
    }];
    
    [[self.pageControl rac_signalForControlEvents:(UIControlEventValueChanged)] subscribeNext:^(id x) {
        
        
        NSIndexPath *indexPath =[NSIndexPath indexPathForItem:self.pageControl.currentPage inSection:0];
        
        
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    }];
    
    
    
    [self prepareCollectionView];
    [self preparePageControl];
    

}



-(void)saveImage{
 // 1. 获取图像
    
//     NSIndexPath *path=self.collectionView.indexPathsForVisibleItems.lastObject;
//    
//    PhotoBrowserCell *cell =[self.collectionView cellForItemAtIndexPath:path];
//
    UIImage *currentImage = self.currentImageView.image;
    
    if (!currentImage) {
        
        [SVProgressHUD showErrorWithStatus:@"没有图像" maskType:1];
        return;
    }
    
    // 2. 保存图像
    UIImageWriteToSavedPhotosAlbum(currentImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    

}


-(void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(id )contextInfo{


    NSString *message = (error==nil)?@"保存成功": @"保存失败";
    [SVProgressHUD showErrorWithStatus:message maskType:1];

}



-(void)preparePageControl{

    self.pageControl.numberOfPages =self.urls.count;
    
    self.pageControl.currentPageIndicatorTintColor =[UIColor redColor];
    
    self.pageControl.pageIndicatorTintColor =[UIColor  greenColor];
    self.pageControl.hidesForSinglePage=YES;
    
    
}

-(void)prepareCollectionView{


    [self.collectionView registerClass:[PhotoBrowserCell class] forCellWithReuseIdentifier:HMPhotoBrowserCellID];
    
    self.collectionView.dataSource =self;
    
    self.collectionView.delegate =self;
    
    UICollectionViewFlowLayout *layout =(UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout;
    
    layout.itemSize=self.view.bounds.size;
    
    layout.scrollDirection =UICollectionViewScrollDirectionHorizontal;
    
    layout.minimumInteritemSpacing=0;
    
    layout.minimumLineSpacing=0;
    
    
    self.collectionView.pagingEnabled =YES;
    
    self.collectionView.bounces=NO;
    
    
}


-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{

    self.pageControl.currentPage = self.collectionView.indexPathsForVisibleItems.lastObject.item;

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   
    return self.urls.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
  
    PhotoBrowserCell*cell =[ collectionView dequeueReusableCellWithReuseIdentifier:HMPhotoBrowserCellID forIndexPath:indexPath];
    
//    cell.backgroundColor =[UIColor randomColor];
    cell.url= self.urls[indexPath.item];
    
    cell.photoDelegate=self;
    return cell;

}


/**
 *  转场动画的kaih
 
 */

//MARK 开始缩放
-(void)photoBrowserCellDidZoomingScale:(CGFloat)scale{
    
    self.photoScale = scale;
   
    [self hideControllers:scale<1];
    
    
    if (scale<1) {
 
        [self startInteractiveTransition:self];
        self.view.alpha=scale;

    }else {
    
        self.view.transform =CGAffineTransformIdentity;
        
        self.view.alpha=1.0;
    }
}



-(void)hideControllers:(BOOL)isHidden{
    self.saveButton.hidden=isHidden;
    self.closeButton.hidden =isHidden;
    
    self.pageControl.hidden = (self.urls.count==1)? YES: isHidden;
    self.view.backgroundColor=isHidden?[ UIColor clearColor]: [UIColor blackColor];
    
    self.collectionView.backgroundColor = isHidden?[UIColor clearColor]:[UIColor blackColor];
    
    
    
}

//MARK 结束缩放

-(void)photoBrowserCellEndZoom{
    
    if (self.photoScale<0.8) {
        [self completeTransition:NO];
    }else{
        // 恢复位置

    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform= CGAffineTransformIdentity;
        
        self.view.alpha=1.0;
    } completion:^(BOOL finished) {
        [self hideControllers:NO];
    }];
    }

}

//MARK: 交互式动画

-(void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext{


    self.view.transform =CGAffineTransformMakeScale(self.photoScale, self.photoScale);
    
    self.view.alpha=self.photoScale;
}





// MARK: - UIViewControllerContextTransitioning - 转场动画上下文协议 - 提供转场动画细节
-(void)completeTransition:(BOOL)didComplete{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (nullable UIView *)containerView{

    return self.view.superview;
}


- (BOOL)isAnimated{

    return NO;
}

- (BOOL)isInteractive;
{
    return YES;
}
- (BOOL)transitionWasCancelled;{

    return YES;
}

- (UIModalPresentationStyle)presentationStyle{
    return UIModalPresentationCustom;
}

- (void)updateInteractiveTransition:(CGFloat)percentComplete{}
- (void)finishInteractiveTransition{}
- (void)cancelInteractiveTransition{}


- (nullable __kindof UIViewController *)viewControllerForKey:(NSString *)key{
    return self;}


- (nullable __kindof UIView *)viewForKey:(NSString *)key NS_AVAILABLE_IOS(8_0){

    return  self.view;}

- (CGAffineTransform)targetTransform NS_AVAILABLE_IOS(8_0){
    return CGAffineTransformIdentity;}

- (CGRect)initialFrameForViewController:(UIViewController *)vc{
    return CGRectZero;
}

- (CGRect)finalFrameForViewController:(UIViewController *)vc{
    return CGRectZero;
}




-(void)closeBtnClick{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UICollectionView *)collectionView{
    
    if (_collectionView==nil) {
        
      _collectionView=[[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
        
    }
    
    return _collectionView;
}


-(UIButton *)saveButton{
    if (_saveButton==nil) {
        _saveButton=[[UIButton alloc] initWithTitle:@"保存" fontSize:14];
        
    }
    return _saveButton;
}


-(UIButton *)closeButton{
    if (_closeButton==nil) {
        _closeButton=[[UIButton alloc] initWithTitle:@"关闭" fontSize:14];

    }
    return _closeButton;
}


-(UIPageControl *)pageControl{
    if (_pageControl==nil) {
        _pageControl=[[UIPageControl alloc] init];
    }
    return _pageControl;
}

@end
